<template>
  <div class="index-model-content sub-margin">
    <div class="content">
      <DetailHead :title="pageTitle" :style="{ width: `calc(100% - ${PanelWidth}px)` }">
        <div slot="btn" class="btn-header">
          <el-button size="small" icon="el-icon-arrow-left" @click.stop="returnOrg">返回</el-button>
        </div>
        <div slot="btns" class="btn-header">
          <el-button v-if="pageType !== 'view'" type="primary" size="small" :loading="loading" @click.stop="fileModel">
            模型存档
          </el-button>
          <!-- <el-button type="primary" size="small" @click.stop="openPreview">评价预览</el-button> -->
        </div>
      </DetailHead>
      <TreeModel
        :source="treeData"
        :style="{ width: `calc(100% - ${PanelWidth}px)` }"
        ref="treeModel"
        @node-select="nodeSelect"
        @menu-click="onMenuClick"></TreeModel>
      <IndexPanel
        :node-info="nodeInfo"
        :tree-info="treeData"
        @switch="onSwitchChange"
        @update-success="onUpdateSuccess"></IndexPanel>
    </div>
    <!-- 添加指标/模型弹窗 -->
    <XnDialog
      custom-class="branch_dialog"
      title="添加指标/模型"
      :visible.sync="dialogVisible"
      @close="onClose"
      width="360px"
      :z-index="999">
      <div class="dialog_con">
        <el-form label-position="top" size="medium">
          <el-form-item label="请选择添加类型">
            <el-radio-group v-model="modelType">
              <el-radio label="06">指标</el-radio>
              <el-radio label="05">模型</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog_footer">
        <el-button size="small" @click.stop="onClose">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm" :loading="loading">确 认</el-button>
      </div>
    </XnDialog>

    <!-- 评价预览弹窗 -->
    <PreviewDialog :view-id="treeData.busId" ref="previewDialog" :visible.sync="previewDialogVisible"></PreviewDialog>
  </div>
</template>
<script>
import IndexPanel from './components/IndexPanel'
import DetailHead from './components/DetailHead.vue'
import TreeModel from './components/TreeModel.vue'
import PreviewDialog from './components/PreviewDialog.vue'
import XnDialog from '@com/xnDialog.vue'
import {
  initModelTree,
  getModelTreeInfo,
  addSubordinate,
  addSibling,
  copyCreate,
  deleteModel,
  keepModelInFile,
} from '@api/modules/indexModel.js'
export default {
  name: 'indexDetail',
  components: {
    DetailHead,
    IndexPanel,
    TreeModel,
    PreviewDialog,
    XnDialog,
  },
  data() {
    return {
      tenantId: '',
      pageTitle: '',
      PanelWidth: 360,
      nodeInfo: {}, // 选中的节点信息
      curNode: {}, // 当前操作的节点信息
      treeData: {}, // 模型树信息
      dialogVisible: false,
      loading: false,
      modelType: '06', // 指标-06，模型-05
      menuClickType: '', // 菜单点击类型
      editing: false,
      previewDialogVisible: false,
    }
  },
  computed: {
    pageType() {
      return this.$route.query.type || 'add'
    },
  },
  created() {
    this.getModelTree()
  },
  methods: {
    // 获取模型树信息
    getModelTree(page) {
      const { type = '', tenantId = '', id = '' } = this.$route.query || {}
      let apiName = null
      let oneParam = null
      if (type === 'add' && !page) {
        apiName = initModelTree
        oneParam = tenantId
      } else {
        apiName = getModelTreeInfo
        oneParam = id || this.treeData.busId
      }
      apiName(oneParam).then(res => {
        if (res.code === 0 || res.status === 200) {
          this.pageTitle = res.data.assessName || ''
          this.treeData = res.data || {}
          this.$nextTick(() => {
            this.onNodeSelect(res.data)
          })
        }
      })
    },
    // 树图选中的节点
    nodeSelect(obj) {
      this.onNodeSelect(obj)
    },
    onNodeSelect(obj) {
      const newObj = JSON.parse(JSON.stringify(obj))
      if ((newObj.children && newObj.children.length === 0) || !newObj.children) {
        newObj.isLeaf = true
      } else {
        newObj.isLeaf = false
      }
      delete newObj.children
      this.nodeInfo = newObj
    },
    // 指标/模型信息栏展开/折叠
    onSwitchChange(bool) {
      this.PanelWidth = bool ? 360 : 38
      this.$refs.treeModel.initChart()
    },
    // 指标/模型数据保存成功
    onUpdateSuccess() {
      this.getModelTree('save')
    },
    openDialog() {
      this.dialogVisible = true
    },
    onClose() {
      this.dialogVisible = false
      this.loading = false
      this.modelType = '06'
      this.menuClickType = ''
      this.curNode = {}
    },
    submitForm() {
      if (this.loading) {
        return false
      }
      this.loading = true
      if (this.menuClickType === 'addNext') {
        this.addNextNode(this.curNode)
      } else if (this.menuClickType === 'addSibling') {
        this.addSiblingNode(this.curNode)
      }
    },
    // 监听右键菜单项的点击事件
    onMenuClick(type, node) {
      this.menuClickType = type
      this.curNode = node
      switch (type) {
        case 'addNext':
        case 'addSibling':
          this.openDialog()
          return false
        case 'copy':
          this.copyNode(node)
          return false
        case 'delete':
          this.deleteNode(node)
          return false
        default:
          return false
      }
    },
    // 添加下一级
    addNextNode(node) {
      addSubordinate({ id: node.busId, type: this.modelType })
        .then(res => {
          if (res.status === 200 || res.code === 0) {
            this.onClose()
            this.$refs.treeModel.hideMenu()
            this.$message.success(this.modelType === '05' ? '添加模型成功' : '添加指标成功')
            this.getModelTree('add')
          } else {
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 添加同一级
    addSiblingNode(node) {
      addSibling({ id: node.busId, type: this.modelType })
        .then(res => {
          if (res.status === 200 || res.code === 0) {
            this.onClose()
            this.$refs.treeModel.hideMenu()
            this.$message.success(this.modelType === '05' ? '添加模型成功' : '添加指标成功')
            this.getModelTree('add')
          } else {
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 复制并创建指标
    copyNode(node) {
      copyCreate(node.busId).then(res => {
        if (res.status === 200 || res.code === 0) {
          this.$refs.treeModel.hideMenu()
          this.$message.success(node.busType === '05' ? '复制创建模型成功' : '复制创建指标成功')
          this.getModelTree('copy')
        }
      })
    },
    // 删除节点
    deleteNode(node) {
      const delTips = `确定要删除${node.busType === '05' ? '模型' : '指标'} “${node.assessName}”？`
      this.$confirm(delTips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteModel(node.busId).then(res => {
            if (res.status === 200 || res.code === 0) {
              this.$refs.treeModel.hideMenu()
              this.$message.success(node.busType === '05' ? '删除模型成功' : '删除指标成功')
              this.getModelTree('del')
            }
          })
        })
        .catch(() => {
          this.$refs.treeModel.hideMenu()
          this.$message.info('取消操作')
        })
    },
    // 模型归档
    fileModel() {
      const resScore = this.checkModelScore(this.treeData)
      if (Number(this.treeData.assessScore) !== resScore) {
        this.$confirm('所有指标的分数总和与根模型的分数不相等，请修改指标或者模型的分数。', '错误', {
          confirmButtonText: '知道了',
          showCancelButton: false,
          type: 'error',
        })
          .then(() => {
            return false
          })
          .catch(() => {
            return false
          })
      } else {
        if (this.loading) {
          return false
        }
        this.loading = true
        keepModelInFile(this.treeData.busId)
          .then(res => {
            this.loading = false
            if (res.status === 200 || res.code === 0) {
              this.$message.success('模型存档成功')
            }
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    // 检查模型分数是否合规
    checkModelScore(data) {
      if (data.children && data.children.length) {
        let totalScore = 0
        data.children.forEach(item => {
          totalScore += this.checkModelScore(item)
        })
        return totalScore
      } else {
        return Number(data.assessScore)
      }
    },
    // 打开预览弹窗
    openPreview() {
      this.previewDialogVisible = true
    },
    returnOrg() {
      this.$router.go(-1)
    },
  },
}
</script>
<style lang="scss" scoped>
@import './detail.scss';
@import '@styles/layout.scss';
.index-model-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  .content {
    flex: 1;
    padding: 20px 0;
    // margin-top: 20px;
  }
}
</style>
